﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
using Common.Model;
using Common.Util;
using Newtonsoft.Json.Linq;
using pinduoduo;
using pinduoduo.Model;
using pinduoduo.Service;
using pinduoduo.Util;
using Tk.Soc.Share.Common.Helpers;

namespace 群发广告
{
    public partial class Form1 : Form
    {
        private ChromiumWebBrowser chromeBrowser;

        private PddTokenService pddTokenService  = new PddTokenService();


        private IList<PddToken> pddTokens = new List<PddToken>();

        public Form1()
        {
            InitializeComponent();
            InitializeChromium();

        }

        //初始化浏览器并启动
        public void InitializeChromium()
        {
            var settings = new CefSettings
            {
                Locale = "zh-CN"
            };

            settings.CachePath = AppDomain.CurrentDomain.BaseDirectory + "caches\\";
            settings.PersistSessionCookies = true;
            settings.PersistUserPreferences = true;

            Cef.Initialize(settings);

            chromeBrowser = new ChromiumWebBrowser("http://yangkeduo.com/");

            chromeBrowser.KeyboardHandler = new CEFKeyBoardHander();

            this.panel1.Controls.Add(chromeBrowser);
            //SetProxy(chromeBrowser, "");
        }

        async private void SetProxy(ChromiumWebBrowser cwb, string Address)
        {
            await Cef.UIThreadTaskFactory.StartNew(delegate
            {
                var rc = cwb.GetBrowser().GetHost().RequestContext;
                var v = new Dictionary<string, string>();
                v["mode"] = "fixed_servers";
                v["server"] = Address;
                string error;
                bool success = rc.SetPreference("proxy", v, out error);
                if (!string.IsNullOrWhiteSpace(error))
                {
                    MessageBox.Show(error, "Tip", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            });

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(this.proxy.Text))
            {
                SetProxy(chromeBrowser, this.proxy.Text);
            }
            else {
                SetProxy(chromeBrowser, "");
            }
          
        }

        private void Form1_Load(object sender, EventArgs e)
        {
             var pddTokens = pddTokenService.GetAllToken();
          
            this.dataGridView1.DataSource = null;
            this.dataGridView1.DataSource = new BindingList<PddToken>(pddTokens.Where(x => x.account_type != 1).ToList());
        }

        private string pddurl = "http://yangkeduo.com/";

        private async void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                return;
            }
            PddToken pddToken = this.dataGridView1.Rows[e.RowIndex].DataBoundItem as PddToken;
            if (pddToken == null)
            {
                return;
            }
          
            //await chromeBrowser.GetCookieManager(null).DeleteCookiesAsync(pddurl, "PDDAccessToken");
            //await chromeBrowser.GetCookieManager(null).DeleteCookiesAsync(pddurl, "pdd_user_id");

            //var PDDAccessToken = new CefSharp.Cookie
            //{
            //    Path = "/",
            //    Domain = "yangkeduo.com",
            //    Creation = DateTime.Today,
            //    Expires = DateTime.Today.AddDays(30),
            //    Name = "PDDAccessToken",
            //    Value = pddToken.PDDAccessToken
            //};
            //var pdd_user_id = new CefSharp.Cookie
            //{
            //    Path = "/",
            //    Domain = "yangkeduo.com",
            //    Creation = DateTime.Today,
            //    Expires = DateTime.Today.AddDays(30),
            //    Name = "pdd_user_id",
            //    Value = pddToken.pdd_user_id
            //};
            //await chromeBrowser.GetCookieManager(null).SetCookieAsync(pddurl, pdd_user_id);
            //await chromeBrowser.GetCookieManager(null).SetCookieAsync(pddurl, PDDAccessToken);
            //string url1 = "http://mobile.yangkeduo.com/personal_profile.html";
            //chromeBrowser.Load(url1);

            if (!string.IsNullOrWhiteSpace(pddToken.PDDAccessToken))
            {
                var pddUserInfo = await PddApi.GetPddMyInfo(pddToken.pdd_user_id, pddToken.PDDAccessToken);

                if (pddUserInfo.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    pddToken.status = "正常";
                }
                else if (pddUserInfo.Content.Contains("error_code"))
                {
                    pddToken.status = "过期";
                }
                else if (pddUserInfo.StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    pddToken.status = "未知";
                }
            }
            else
            {
                pddToken.status = "未知";
            }
            pddTokenService.UpdateToken(pddToken, true);
            this.dataGridView1.Refresh();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            chromeBrowser.Back();
        }

        private void button15_Click(object sender, EventArgs e)
        {
            string url = "http://yangkeduo.com/";
            chromeBrowser.Load(url);
        }

        private void button13_Click(object sender, EventArgs e)
        {
            string url = "http://yangkeduo.com/addresses.html?bind_phone_scene=personal_create_address&refer_page_name=personal";
            chromeBrowser.Load(url);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //chromeBrowser.Load(this.url.Text);
        }

        private void button17_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件夹";
            dialog.Filter = "所有文件(*.txt)|*.txt";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string file = dialog.FileName;
                string text = File.ReadAllText(file);
                if (string.IsNullOrWhiteSpace(text))
                {
                    MessageBox.Show("数据为空");
                    return;
                }
                string[] striparr = text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                var PddTokenList = pddTokenService.GetAllToken();
                foreach (var item in striparr)
                {
                    try
                    {
                        string[] sArray1 = item.Split(new char[4] { '-', '-', '-', '-' }, StringSplitOptions.RemoveEmptyEntries);
                        if (sArray1.Length != 3)
                        {
                            continue;
                        }
                        string qqOrPhone = sArray1[0];
                        string uid = sArray1[1];
                        string token = sArray1[2];
                        PddToken pddToken = new PddToken();
                        pddToken.pdd_user_id = uid;
                        pddToken.PDDAccessToken = token;
                        var pddT = PddTokenList.Where(x =>
                        {
                            return x.pdd_user_id == uid;
                        }).FirstOrDefault();
                        if (pddT != null)
                        {
                            pddToken.id = pddT.id;
                            pddTokenService.UpdateToken(pddToken);
                            //DataBaseHelper.SqLiteDBCon.Update<PddToken>(pddToken);
                        }
                        else
                        {
                            pddTokenService.InsertToken(pddToken);
                            //var reslut = DataBaseHelper.SqLiteDBCon.Insert<PddToken>(pddToken);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Logger.Error("导入小号失败", ex);
                    }

                }

                var tokens = pddTokenService.GetAllToken();
                pddTokens.Clear();
                pddTokens = pddTokens.Concat(tokens).ToList();

                this.dataGridView1.DataSource = new BindingList<PddToken>(pddTokens.Where(x => x.account_type != 1).ToList());
               
            }
        }

        private async void button5_Click(object sender, EventArgs e)
        {
            string maillID = this.maillID.Text;
            string proxy = this.proxy.Text;
            var pddToken = this.dataGridView1.CurrentRow.DataBoundItem as PddToken;
       
            ClientWebSocket webSocket = new ClientWebSocket();
            if (!string.IsNullOrWhiteSpace(proxy))
            {
                webSocket.Options.Proxy = RestClientUtil.CreateWebProxy(proxy);
            }
            else 
            {
                MessageBox.Show("没代理可不行啊！！！");
                return;
            }

            try
            {
                await webSocket.ConnectAsync(new Uri(PddApi.ChatWsUrl + pddToken.PDDAccessToken), new CancellationTokenSource(PddApi.millisecondsDelay).Token);
                if (!await PddApi.ChatWsIsAuth(webSocket))
                {
                    msgRichTextBox.AppendText("小号进入聊天失败\r\n");
                    return;
                }

                string result;

                if (!string.IsNullOrWhiteSpace(chatMsg.Text))
                {
                    result = await PddApi.SendText(webSocket, chatMsg.Text, pddToken.pdd_user_id, maillID);
                    msgRichTextBox.AppendText("发送消息返回：" + result + "\r\n");
                }

                foreach (var item in this.listView1.Items)
                {
                    ListViewItem listViewItem = item as ListViewItem;
                    result = await PddApi.UploadAndSendImage(webSocket, maillID, pddToken, listViewItem.Name, proxy);
                    msgRichTextBox.AppendText("发送图片返回：" + result + "\r\n");
                }

              
                //string json = "{\"cmd\":\"send_message\",\"message\":{\"from\":{\"role\":\"user\",\"uid\":\"4619842368694\"},\"to\":{\"role\":\"mall\",\"uid\":\"627671\"},\"content\":\"https://t00img.yangkeduo.com/chat/chat_user_upload/2021-05-18/9982935159702f1bed3ec1590f8c3fd9.jpeg\",\"type\":1},\"version\":2,\"refer_page_name\":\"mall\",\"login_app_id\":\"\",\"anti_content\":\"0apAfqnUpshyy9EVclZ4CkCgVXpXCOtKmD87Aor-xGwdnzbk7PxKBImqDIgsRAPr7XmTRXXtsPUTBGKCHpPC9wPYPVWoX5XYGiCoj9VCETTqYANJaXHrJOl1FpzKFmRIDNbaJ-IN-pOLWKIu66BU10BVqtKNA0L58qsaNZRWd8W-yOKMlWKrtk1x-G9PLEdn9UMG6CSFtBPjABE3Mr9mHS5eeY6yA8EwK6QCok4BBsoP8X5FhUK0e-WyfCjNSo-XYIy_JW9gRkGGB0erj_K9Uc0uwNC4lST-vIFqoKtlNcnyohlnzV1VCLVEwC-VCZ98V-sqbOjb43JhQWGnbTzhfVAM1RU5F5ottt1SzVqOmRpTfYXe6PS9yJwOcdqTQ18QgWLKOxXyb5j8A493LKwxySuqud03r0pJKP5Q-6q7pkmZgj3u3qf-tFzL_cL7Omd4t0mSqlkNvak7V4AadjCtCCc1jLLfrYdGeGdAR2n0RAw3mW4bkruwfkiMih6JM3adT5qrGafdaYQpWrkNmij7Fr4e7uEjY_9XGfA7uJFYIsVzJnZu5hiUYH5jFDhnNnBb3JyT_SAhLjOWGovyMkQpPSA_7FPAydSr6OliLVONjrm_VY7YVWgberDtVxVUovKuWHUfdWcfgU65rb0XqJlAhHkC3Xa\",\"user_agent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36\",\"request_id\":9}";
                //byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(json);
                //await webSocket.SendAsync(new ArraySegment<byte>(byteArray), WebSocketMessageType.Binary, true, CancellationToken.None);
            }
            catch (Exception ex)
            {
                msgRichTextBox.AppendText("发送异常" + ex.Message + "\r\n");
            }
            finally
            {
                webSocket.Abort();
                //await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", new CancellationTokenSource(PddApi.millisecondsDelay).Token);
            }


            //string url = "http://mobile.pinduoduo.com/chat_detail.html?mall_id="+this.maillID.Text+"&goods_id="+this.goodId.Text+"&cat_id_1=17285&page_from=35&is_full_reduction=false&is_full_return=false&refer_page_name=goods_detail&refer_page_id=10014_1620905888814_q2glidocqv&refer_page_sn=10014";
            //chromeBrowser.Load(url);
            //var tokens = pddTokenService.GetAllToken();
            //tokens = pddTokens.Where(x => x.account_type != 1).ToList();
            //4619842368694----DLGZHHEW75UHGFKZ7SU5B2GUR7PZMZSISYV7KLDK3GVNXG4SDFEA110b6b2
            //7009193019259----ZC5YRN52SZYS62L2YM3YXAY2BKU5LCDB5UPEWA3LZ2H6AYTIJ4EQ1137b84
            //2654660758573----FQXFNZC2XNFBTFRXRBTSJYTYDGV5OEWTWVCWICIFRBN2VWJT42EQ1102db8
            // 9077964235595----X5NU66NJRIO3GYBARIHXYKUK3FVSE4OTGQN62SEAVGOP2OBD6ZVQ1134b7e 
            //
            //PddToken pddToken =new PddToken();
            //pddToken.pdd_user_id = "9077964235595";
            //pddToken.PDDAccessToken = "X5NU66NJRIO3GYBARIHXYKUK3FVSE4OTGQN62SEAVGOP2OBD6ZVQ1134b7e";
            //foreach (var pddToken in tokens)
            //{


            //await webSocket.ConnectAsync(new Uri("wss://127.0.0.1:8443/v1"), new CancellationTokenSource(PddApi.millisecondsDelay).Token);

            //if (webSocket.State != WebSocketState.Open)
            //{
            //    return ;
            //}
            //byte[] bufSize = new byte[1 * 1024];
            //ArraySegment<byte> buf = new ArraySegment<byte>(bufSize);
            //WebSocketReceiveResult r = await webSocket.ReceiveAsync(buf, new CancellationTokenSource(5000).Token);
            //string str = System.Text.Encoding.Default.GetString(bufSize);


            //byte[] byteArray = System.Text.Encoding.UTF8.GetBytes("ssssssssss");
            //await webSocket.SendAsync(new ArraySegment<byte>(byteArray), WebSocketMessageType.Binary, true, CancellationToken.None);


            //await webSocket.ReceiveAsync(buf, new CancellationTokenSource(5000).Token);
            // str = System.Text.Encoding.Default.GetString(bufSize);

            //byteArray = System.Text.Encoding.UTF8.GetBytes("7777777777777");
            //await webSocket.SendAsync(new ArraySegment<byte>(byteArray), WebSocketMessageType.Binary, true, CancellationToken.None);

            //string json = "{\"cmd\":\"send_message\",\"message\":{\"from\":{\"role\":\"user\",\"uid\":\"4619842368694\"},\"to\":{\"role\":\"mall\",\"uid\":\"627671\"},\"content\":\"https://t00img.yangkeduo.com/chat/chat_user_upload/2021-05-18/9982935159702f1bed3ec1590f8c3fd9.jpeg\",\"type\":1},\"version\":2,\"refer_page_name\":\"mall\",\"login_app_id\":\"\",\"anti_content\":\"0apAfqnUpshyy9EVclZ4CkCgVXpXCOtKmD87Aor-xGwdnzbk7PxKBImqDIgsRAPr7XmTRXXtsPUTBGKCHpPC9wPYPVWoX5XYGiCoj9VCETTqYANJaXHrJOl1FpzKFmRIDNbaJ-IN-pOLWKIu66BU10BVqtKNA0L58qsaNZRWd8W-yOKMlWKrtk1x-G9PLEdn9UMG6CSFtBPjABE3Mr9mHS5eeY6yA8EwK6QCok4BBsoP8X5FhUK0e-WyfCjNSo-XYIy_JW9gRkGGB0erj_K9Uc0uwNC4lST-vIFqoKtlNcnyohlnzV1VCLVEwC-VCZ98V-sqbOjb43JhQWGnbTzhfVAM1RU5F5ottt1SzVqOmRpTfYXe6PS9yJwOcdqTQ18QgWLKOxXyb5j8A493LKwxySuqud03r0pJKP5Q-6q7pkmZgj3u3qf-tFzL_cL7Omd4t0mSqlkNvak7V4AadjCtCCc1jLLfrYdGeGdAR2n0RAw3mW4bkruwfkiMih6JM3adT5qrGafdaYQpWrkNmij7Fr4e7uEjY_9XGfA7uJFYIsVzJnZu5hiUYH5jFDhnNnBb3JyT_SAhLjOWGovyMkQpPSA_7FPAydSr6OliLVONjrm_VY7YVWgberDtVxVUovKuWHUfdWcfgU65rb0XqJlAhHkC3Xa\",\"user_agent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36\",\"request_id\":9}";
            // byteArray = System.Text.Encoding.UTF8.GetBytes(json);
            //await webSocket.SendAsync(new ArraySegment<byte>(byteArray), WebSocketMessageType.Binary, true, CancellationToken.None);






            //var msg = await  PddApi.SendText(webSocket, "亲，哪里发货！",pddToken.pdd_user_id, "627671");
            //msgRichTextBox.AppendText("发送消息：" + msg + "\r\n");
            //  var   msg = await  PddApi.UploadAndSendImage(webSocket, "627671",pddToken, @"D:\ceshi\1.jpg");
            //  msgRichTextBox.AppendText("发送图片："+msg+"\r\n");
            //}

        }

        private void button10_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件夹";
            dialog.Filter = "所有文件(*.jpg)|*.jpg";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string file = dialog.FileName;
                //FileStream fs = File.Open(file, FileMode.Open);
                //ImageUtil.CutForCustom(fs, "D://test//1.jpg", 900, 1200,70);
                bindListView(file);
            }

        }

        //下面是方法
        private void bindListView(string path)
        {
            imageList1.Images.Add(System.Drawing.Image.FromFile(path));
            listView1.Items.Add(path, System.IO.Path.GetFileName(path), 1);
            listView1.Items[0].ImageIndex = 1;
        }

        private void button11_Click(object sender, EventArgs e)
        {
            var selectedListViewItemCollection = this.listView1.SelectedItems;
            foreach (var item in selectedListViewItemCollection)
            {
                ListViewItem listViewItem = item as ListViewItem;
                imageList1.Images.RemoveByKey(listViewItem.Name);
                listView1.Items.RemoveByKey(listViewItem.Name);
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            new AddToken().ShowDialog();
            var pddTokens = pddTokenService.GetAllToken();

            this.dataGridView1.DataSource = null;
            this.dataGridView1.DataSource = new BindingList<PddToken>(pddTokens.Where(x => x.account_type != 1).ToList());
        }

        private void button6_Click(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            string url = "http://http.tiqu.letecs.com/getip3?num=1&type=1&pro=&city=0&yys=0&port=1&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1&regions=&gm=4";
            string ip=  IPProxy.GetZMNewIp(url);
            this.proxy.Text= ip;
        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("您确定清空吗", "提示框", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.OK)
            {
                pddTokenService.DelAllToken();

                var pddTokens = pddTokenService.GetAllToken();

                this.dataGridView1.DataSource = null;
                this.dataGridView1.DataSource = new BindingList<PddToken>(pddTokens.Where(x => x.account_type != 1).ToList());
            }
       
        }

        private void button12_Click(object sender, EventArgs e)
        {

            var pddToken = this.dataGridView1.CurrentRow.DataBoundItem as PddToken;
            if (pddToken == null) {
                return;
            }
            DialogResult dr = MessageBox.Show("您确定删除吗", "提示框", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.OK)
            {
                pddTokenService.DelToken(pddToken);

                var pddTokens = pddTokenService.GetAllToken();

                this.dataGridView1.DataSource = null;
                this.dataGridView1.DataSource = new BindingList<PddToken>(pddTokens.Where(x => x.account_type != 1).ToList());
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            SetProxy(chromeBrowser, this.BrowserProxy.Text);
        }

        private void button7_Click(object sender, EventArgs e)
        {
            chromeBrowser.Load(urlTextBox.Text);
        }

        private async void button9_Click(object sender, EventArgs e)
        {
          var sss=  await chromeBrowser.GetSourceAsync();
        }

        private  void button13_Click_1(object sender, EventArgs e)
        { 
            //new TestWindow().Show();
            //var pddToken = this.dataGridView1.CurrentRow.DataBoundItem as PddToken;
            //var res = await pinduoduo.PddApi.GetRegions(pddToken);
            //if (res.StatusCode == System.Net.HttpStatusCode.OK)
            //{
            //    var regions = JsonHelper.DeserializeObject<Regions>(res.Content);
            //    RegionsItem curRegionsItem = null;
            //    foreach (var regionItem in regions.regions)
            //    {

            //    }
            //}
        }

       public async void GetRegions(int regionId, PddToken pddToken) 
       {

            var res = await pinduoduo.PddApi.GetRegions(pddToken, regionId);
            if (res.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var regions = JsonHelper.DeserializeObject<Regions>(res.Content);
                Console.WriteLine(res.Content);
              
                foreach (var regionItem in regions.regions)
                {
                    if (regionItem.region_type == 3) 
                    {
                        break;
                    }
                    GetRegions(regionItem.region_id, pddToken);
                }
            }
        }

        private void button14_Click(object sender, EventArgs e)
        {

        }

        private async void button15_Click_1(object sender, EventArgs e)
        {
            string script = @"(function() { return  window.rawData.store;})()";

            await chromeBrowser.EvaluateScriptAsync(script).ContinueWith(x =>
            {
                var response = x.Result;

                if (response.Success && response.Result != null)
                {
                    var jo = JObject.FromObject(response.Result);
                }
            });
        }
    }
}
